package com.stud.postgres.jdbc;

import com.stud.postgres.util.Toolkit;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.postgresql.util.PGobject;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes({String.class})
public class GeometryTypeHandler extends BaseTypeHandler<String> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {

        PGobject object = new PGobject();
        object.setType("geometry");
        object.setValue(Toolkit.geometryJson2Binary(parameter));

//        PGgeometry pGgeometry = new PGgeometry(parameter);
//        Geometry geometry = pGgeometry.getGeometry();
//        geometry.setSrid(4326);
        ps.setObject(i, object);
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return Toolkit.geometryBinary2Json(rs.getString(columnName));
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return Toolkit.geometryBinary2Json(rs.getString(columnIndex));
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return Toolkit.geometryBinary2Json(cs.getString(columnIndex));
    }

    @Override
    public String getResult(ResultSet rs, String columnName) throws SQLException {
        return Toolkit.geometryBinary2Json(rs.getString(columnName));
    }
}
 